package com.example.tang.zhayan.ui;

import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.tang.zhayan.R;
import com.example.tang.zhayan.adapter.SplashImgAdapter;
import com.example.tang.zhayan.bean.BaseDesignerDetail;
import com.example.tang.zhayan.bean.BaseDesignerDetailAttribute;
import com.example.tang.zhayan.bean.DesignerDetailBuyItem;
import com.example.tang.zhayan.bean.DesignerDetailItem;
import com.example.tang.zhayan.constant.PathConstant;
import com.example.tang.zhayan.utils.ResultParamsUtils;
import com.example.tang.zhayan.utils.WindowsUtils;

import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.onekeyshare.OnekeyShare;


/**
 * Created by tang on 2015/12/16.
 */

/**
 * Created by tang on 2015/12/16.
 */
@ContentView(R.layout.activity_buy)
public class BuyDetailsActivity extends AppCompatActivity implements View.OnClickListener {
    //UI
    @ViewInject(R.id.viewpager_buy)
    private ViewPager viewPagerBuy;
    @ViewInject(R.id.tv_buy_old)
    private TextView oldPrice;
    @ViewInject(R.id.tv_buy_new)
    private TextView newPrice;
    @ViewInject(R.id.tv_buy_num)
    private TextView txtNum;
    @ViewInject(R.id.iv_buy_attribute)
    private ImageView ivAttribute;
    @ViewInject(R.id.iv_buy_ask)
    private ImageView ivAsk;
    @ViewInject(R.id.iv_buy_know)
    private ImageView ivKnow;
    @ViewInject(R.id.img_works_search)
    private ImageView ivSearch;

    @ViewInject(R.id.tv_buy)
    private TextView tv_buy;

    //数据
    private SplashImgAdapter adapter;
    private List<ImageView> imageViewList;
    private Map<String, String> map;
    private String id;
    private String memberId;
    private List<DesignerDetailBuyItem> lisItem;
    private List<String> lisImgUrl;
    private PopupWindow popupWindow;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        popupWindow = new PopupWindow();
        //设置购买的监听
        tv_buy.setOnClickListener(this);
        initList();
        getId();
        adapter = new SplashImgAdapter(imageViewList);
        viewPagerBuy.setAdapter(adapter);
        getData();
    }

    /**
     * 添加Popupwindow
     */
    private void addPopupWindow(String str1, String str2, View v) {
        View view = getLayoutInflater().inflate(R.layout.buy_popupwindow_view, null);
        TextView textName = (TextView) view.findViewById(R.id.buy_details_name);
        TextView textContext = (TextView) view.findViewById(R.id.buy_details_context);
        TextView textHide = (TextView) view.findViewById(R.id.popup_window_hide);
        textContext.setText(str2);
        textName.setText(str1);
        final AbsListView.LayoutParams params = new AbsListView.LayoutParams(new WindowsUtils(this)
                .getScreenWidth(), new WindowsUtils(this).getScreenHeight());
        view.setLayoutParams(params);
        popupWindow = new PopupWindow(view, new WindowsUtils(this)
                .getScreenWidth(), new WindowsUtils(this).getScreenHeight());
        popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
        popupWindow.setOutsideTouchable(true);

        //PopupWindow的隐藏点击事件
        textHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        //在底部显示Popupwindow
        popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
    }


    /**
     * 分享
     */
    private void showShare(String str) {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
//        oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//        oks.setTitle(getString(R.string.share));
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
//        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText(str);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
//        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//        oks.setSiteUrl("http://sharesdk.cn");
// 启动分享GUI
        oks.show(this);
    }


    /**
     * viewPager的滑动事件
     */
    private void addListener() {
        viewPagerBuy.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                txtNum.setText((position + 1) + "/" + (lisImgUrl.size()));
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    /**
     * 点击显示Popupwindow详情
     */

    public void showPopupWindow() {

    }

    private void initList() {
        imageViewList = new ArrayList<>();
        lisImgUrl = new ArrayList<>();
        lisItem = new ArrayList<>();
        map = new HashMap<>();
    }


    /**
     * 给map加入值
     */
    private void initMap() {
        map.put("id", id);
        map.put("memberId", memberId);
    }

    /**
     * 获取数据源
     */
    public void getData() {
        x.http().post(ResultParamsUtils.getIDParams(PathConstant.WORKS_DETAILS, map), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                BaseDesignerDetail buy = JSON.parseObject(s, BaseDesignerDetail.class);
                final DesignerDetailItem data = buy.getData().getItem();
                if (data != null) {
                    initListImgUrl(data);
                    for (int i = 0; i < lisImgUrl.size(); i++) {
                        ImageView view = new ImageView(BuyDetailsActivity.this);
                        view.setScaleType(ImageView.ScaleType.FIT_XY);
                        x.image().bind(view, lisImgUrl.get(i));
                        imageViewList.add(view);
                    }
                    adapter.notifyDataSetChanged();
                    oldPrice.setText("￥" + data.getOld_prc() + ".00");
                    oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    newPrice.setText("￥" + data.getNew_prc() + ".00");
                    /**
                     * 编语点击事件
                     */
                    ivAsk.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            addPopupWindow(data.getItem_name(), data.getStory(), v);
                        }
                    });
                    /**
                     * 须知点击事件
                     */
                    ivKnow.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            addPopupWindow(data.getItem_name(), data.getNeed_to_know(), v);
                        }
                    });

                    /**
                     * 分享商品的数据
                     */
                    ivSearch.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showShare(data.getItem_name() + "" + data.getStory() + "" + data.getNeed_to_know());
                        }
                    });
                    /**
                     * 属性点击事件
                     */
                    ivAttribute.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(final View v) {
                            map.clear();
                            map.put("id", id);
                            x.http().post(ResultParamsUtils.getIDParams(PathConstant.WORKS_ATTRIBUTE, map), new CommonCallback<String>() {
                                @Override
                                public void onSuccess(String s) {
                                    BaseDesignerDetailAttribute item = JSON.parseObject(s, BaseDesignerDetailAttribute.class);
                                    String str = item.getData().getList().get(0).getDetail() + "\n"
                                            + item.getData().getList().get(0).getProperty() + "\n"
                                            + item.getData().getList().get(1).getDetail() + "\n"
                                            + item.getData().getList().get(1).getProperty() + "\n";
                                    addPopupWindow(str, "", v);
                                }

                                @Override
                                public void onError(Throwable throwable, boolean b) {

                                }

                                @Override
                                public void onCancelled(CancelledException e) {

                                }

                                @Override
                                public void onFinished() {

                                }
                            });
                        }
                    });
                    addListener();
                }
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    /**
     * 得到图片的地址
     */
    private void initListImgUrl(DesignerDetailItem item) {
        getUrl(item.getImg1());
        getUrl(item.getImg2());
        getUrl(item.getImg3());
        getUrl(item.getImg4());
        getUrl(item.getImg5());
    }

    /**
     * 判断图片地址是否为空
     *
     * @param str
     */
    public void getUrl(String str) {
        if (!str.equals("")) {
            lisImgUrl.add(str);
        }

    }

    /**
     * 获取传过来的id值
     */
    public void getId() {
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        memberId = intent.getStringExtra("memberId");
        initMap();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_buy:

                break;
        }
    }
}